package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.CustomerReservationMapper;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import com.zzyl.vo.TimeCountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import java.util.List;


@Slf4j
@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {
    @Autowired
    CustomerReservationMapper customerReservationMapper;


    @Override
    public Integer countCancelledReservation(Long updateBy) {


        Integer count = customerReservationMapper.countCancelledReservation(updateBy);

        return count;
    }

    @Override
    public List<TimeCountVo> countReservationsForEachTime(LocalDateTime handleTime) {
        LocalDateTime start = LocalDateTimeUtil.beginOfDay(handleTime);
        LocalDateTime end = LocalDateTimeUtil.endOfDay(handleTime);
        List<TimeCountVo> list = customerReservationMapper.countReservationsForEachTime(start,end);
        return list;
    }

    @Override
    public void add(ReservationDto reservationDto) {

        Reservation reservation = new Reservation();
        BeanUtil.copyProperties(reservationDto, reservation);
        reservation.setStatus(0);

        customerReservationMapper.add(reservation);

    }


    /**
     * 分页
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResponse<ReservationVo> selectByPage(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Page<List<ReservationVo>> page = customerReservationMapper.selectByPage(status);

        log.info("Fetched page response: {}", page);
        if (page == null) {
          throw new BaseException(BasicEnum.BUSINESS_ERROR);

        }
        return PageResponse.of(page, ReservationVo.class);
    }


    /**
     * 取消预约
     * @param id
     */
    @Override
    public void cancelReservation(Long id) {
       Reservation reservation= customerReservationMapper.selectById(id);
       if (reservation==null){
           throw new BaseException(BasicEnum.RESERVATION_NOT_EXIST);
       }
       if (reservation.getStatus()!=0){
           throw new BaseException(BasicEnum.RESERVATION_STATUS_ERROR);
       }
        customerReservationMapper.cancelReservation(reservation);
    }
}
